using System;
using System.IO;
using UnityEngine;

namespace Voodoo.Sauce.Internal.CrossPromo.Utils
{
	internal static class CacheManager
	{
		private const string CacheDirectoryName = "VoodooAds";

		public static readonly string Path = string.Format("{0}/{1}/", Application.temporaryCachePath, "VoodooAds");

		public static void CreateCacheIfNoExist()
		{
			try
			{
				CreateDirectoriesIfNoExist(Path);
			}
			catch (Exception ex)
			{
				VoodooLog.LogW(VoodooCrossPromo.TAG, ex.ToString());
			}
		}

		public static void WriteFile(string filePath, byte[] bytes)
		{
			try
			{
				CreateDirectoriesIfNoExist(Path + filePath, fromFilePath: true);
				File.WriteAllBytes(Path + filePath, bytes);
			}
			catch (Exception ex)
			{
				VoodooLog.LogW(VoodooCrossPromo.TAG, ex.ToString());
			}
		}

		public static string[] GetAllFilesFromCache()
		{
			try
			{
				return Directory.GetFiles(Path, "*.*", SearchOption.AllDirectories);
			}
			catch (Exception)
			{
				return new string[0];
			}
		}

		public static bool IsFileExist(string filePath)
		{
			try
			{
				return File.Exists(Path + filePath);
			}
			catch (Exception)
			{
				return false;
			}
		}

		public static void DeleteFile(string filePath)
		{
			try
			{
				File.Delete(filePath);
			}
			catch (Exception arg)
			{
				VoodooLog.Log(VoodooCrossPromo.TAG, "Deleting file failed " + arg);
			}
		}

		public static bool CompareTwoFilesName(string path1, string path2)
		{
			string key = PlayerPrefsUtils.GetKey(path1);
			string key2 = PlayerPrefsUtils.GetKey(path2);
			try
			{
				return key.Equals(key2);
			}
			catch (Exception)
			{
				return false;
			}
		}

		public static string GetCurrentDirectory(string filePath)
		{
			return System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName(filePath));
		}

		private static void CreateDirectoriesIfNoExist(string path, bool fromFilePath = false)
		{
			if (fromFilePath)
			{
				string directoryName = System.IO.Path.GetDirectoryName(path);
				if (string.IsNullOrEmpty(directoryName))
				{
					throw new Exception("Wrong Directory Name");
				}
				path = directoryName;
			}
			if (!Directory.Exists(path))
			{
				Directory.CreateDirectory(path);
			}
		}
	}
}
